// import useStore from '@/store';
import useStore from '..'
import request from '@/utils/request'
import { defineStore } from 'pinia'
import { ApiRes } from '@/types/data'
import { Profile } from '@/types/user'
import { getProfile, setProfile, removeProfile } from '@/utils/storage'
const useUserStore = defineStore('user', {
  state() {
    return {
      // profile: {} as Profile
      profile: getProfile() // 获取是从localStorage中
    }
  },
  actions: {
    // 用户名和密码登录
    async login(account: string, password: string) {
      const res = await request.post<ApiRes<Profile>>('/login', {
        account,
        password
      })
      // 保存用户信息
      this.profile = res.data.result
      // 存储到本地中
      setProfile(res.data.result)
    },
    // 获取手机验证码
    async getMobileMsg(mobile: string) {
      await request.get('/login/code', {
        params: {
          mobile
        }
      })
    },
    // 手机号和验证码登录
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<ApiRes<Profile>>('/login/code', {
        mobile,
        code
      })
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      // 存储到本地中
      setProfile(res.data.result)
    },
    // 移除信息
    logout() {
      this.profile = {} as Profile
      removeProfile()
      // 清空购物车
      const { cart } = useStore()
      cart.clearCart()
    }
  }
})

export default useUserStore